#!/bin/bash

tclangDir=$(dirname "$(readlink -f "$0")")
compiler=clang-13
opt=opt-13
llc=llc-13
argList=""
obj=""
readingObj=0
unsupported=("-fno-gnu-unique")
for i in "$@"; do
	if [ "-c" == "$i" ];
	then
		argList+=" -emit-llvm"
	fi
	if [ $readingObj == 1 ];
	then
		readingObj=0
		obj="$i"
	fi
	if [ "-o" == "$i" ];
	then
		readingObj=1
	fi

	unsupp=0
	for j in ${unsupported[@]}
	do
   		[ "$i" == "$j" ] && unsupp=1
	done

	if [ $unsupp == 1 ];
	then
		continue
	fi
	argList+=" $i"
done

#set -x
linking=0
case "$obj" in
    *.o) linking=0 ;;
    *.so)     linking=1 ;;
    *.a)  linking=1 ;;
    *) linking=1;;
esac

if [ "$linking" == "0" ];
then
	comp_bc="$compiler $argList"
	#echo $comp_bc
	eval $comp_bc
	opt_cmd="$opt -enable-new-pm=0 -load '$tclangDir/liblkin.so' -lookin $obj > '$obj.opt'"
	#echo $opt_cmd
	eval $opt_cmd
	llc_cmd="$llc -filetype=obj --relocation-model=pic '$obj.opt' -o $obj"
	#echo $llc_cmd
	eval $llc_cmd
fi

if [ "$linking" == "1" ];
then
	link_cmd="$compiler -Wl,-rpath,'$tclangDir' '$tclangDir/liblkinDummy.so' $argList"
	#echo $link_cmd
	eval $link_cmd
fi

